<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>阅读器</title>
    <style>
        /* 1. 基础样式重置 + 全局变量 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Roboto', 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }

        :root {
            /* 白天模式变量 */
            --bg-color: #f7f7f7;
            --text-color: #333;
            --sidebar-bg: #fff;
            --sidebar-active: #e1f5fe;
            --control-bg: #fff;
            --border-color: #eee;
            --image-bg: #fff;
        }

        /* 夜间模式变量覆盖 */
        body.night {
            --bg-color: #1a1a1a;
            --text-color: #ccc;
            --sidebar-bg: #2d2d2d;
            --sidebar-active: #4a4a4a;
            --control-bg: #2d2d2d;
            --border-color: #3d3d3d;
            --image-bg: #2d2d2d;
        }

        /* 护眼绿模式 */
        body.eye-green {
            --bg-color: #e6f4ea;
            --text-color: #0d3a18;
            --sidebar-bg: #d4eadc;
            --sidebar-active: #b3d9be;
            --control-bg: #d4eadc;
            --border-color: #b3d9be;
            --image-bg: #d4eadc;
        }

        /* 护眼黄模式 */
        body.eye-yellow {
            --bg-color: #FFFDE7;
            --text-color: #5D4037;
            --sidebar-bg: #FFF9C4;
            --sidebar-active: #FFF59D;
            --control-bg: #FFF9C4;
            --border-color: #FFF59D;
            --image-bg: #FFF9C4;
        }

        /* 护眼褐模式 */
        body.eye-brown {
            --bg-color: #f5f0e8;
            --text-color: #5c4033;
            --sidebar-bg: #e8e0d5;
            --sidebar-active: #d9c9b8;
            --control-bg: #e8e0d5;
            --border-color: #d9c9b8;
            --image-bg: #e8e0d5;
        }

        body {
            background-color: var(--bg-color);
            color: var(--text-color);
            transition: background-color 0.3s, color 0.3s;
            min-height: 100vh;
        }

        /* 文件选择区域样式 */
        .file-selector {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            padding: 20px;
            text-align: center;
        }

        .file-btn {
            background-color: #2196f3;
            color: white;
            border: none;
            padding: 12px 24px;
            margin-top: 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.2s;
        }

        .file-btn:hover {
            background-color: #0b7dda;
        }

        .file-input {
            display: none;
        }

        .file-info {
            margin-top: 15px;
            color: #666;
            font-size: 14px;
        }

        /* 2. 顶部导航栏 */
        .header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: 50px;
            background-color: var(--control-bg);
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            padding: 0 16px;
            z-index: 100;
            display: none; /* 初始隐藏 */
        }

        .menu-btn {
            background: none;
            border: none;
            color: var(--text-color);
            font-size: 20px;
            cursor: pointer;
            margin-right: 16px;
        }

        .book-title {
            font-size: 16px;
            font-weight: 500;
            flex: 1;
            text-align: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* 3. 侧边章节栏 */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            width: 260px;
            height: 100vh;
            background-color: var(--sidebar-bg);
            border-right: 1px solid var(--border-color);
            transform: translateX(-100%);
            transition: transform 0.3s ease;
            z-index: 101;
            overflow-y: auto;
            padding-top: 60px;
            display: none; /* 初始隐藏 */
        }

        .sidebar.show {
            transform: translateX(0);
        }

        .chapter-list {
            list-style: none;
            padding: 0 16px;
        }

        .chapter-item {
            padding: 12px 8px;
            margin-bottom: 4px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s;
        }

        .chapter-item.active {
            background-color: var(--sidebar-active);
            color: #2196f3;
        }

        .chapter-item:hover {
            background-color: var(--border-color);
        }

        /* 4. 遮罩层 */
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s;
            z-index: 100;
            display: none; /* 初始隐藏 */
        }

        .overlay.show {
            opacity: 1;
            pointer-events: auto;
        }

        /* 5. 主阅读区域 */
        .reader-container {
            max-width: 70%;
            margin: 0 auto;
            padding: 70px 20px 100px; /* 增加底部内边距，为加载指示器留出空间 */
            display: none; /* 初始隐藏 */
        }

        .content {
            font-size: 16px;
            line-height: 1.8;
            letter-spacing: 0.5px;
            margin-bottom: 40px;
        }

        .content p {
            margin-bottom: 24px;
            text-indent: 2em;
        }

        /* 新增：图片样式 */
        .content .image-container {
            margin: 30px auto;
            text-align: center;
            background-color: var(--image-bg);
            padding: 15px;
            border-radius: 8px;
        }
        
        .content img {
            max-width: 100%;
            height: auto;
            border-radius: 4px;
            cursor: zoom-in;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        .content img:hover {
            transform: scale(1.01);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        .content .image-caption {
            margin-top: 10px;
            font-size: 0.9em;
            color: #888;
            font-style: italic;
        }

        /* 新增：图片查看器 */
        .image-viewer {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.9);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 200;
            padding: 20px;
        }
        
        .image-viewer.show {
            display: flex;
        }
        
        .image-viewer img {
            max-width: 100%;
            max-height: 90vh;
            object-fit: contain;
        }
        
        .image-viewer .close-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            color: white;
            background: none;
            border: none;
            font-size: 30px;
            cursor: pointer;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.1);
            transition: background-color 0.2s;
        }
        
        .image-viewer .close-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }

        /* 6. 底部控制栏 */
        .control-bar {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            height: 60px;
            background-color: var(--control-bg);
            border-top: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: space-around;
            padding: 0 16px;
            z-index: 100;
            display: none; /* 初始隐藏 */
        }

        .control-btn {
            background: none;
            border: none;
            color: var(--text-color);
            font-size: 14px;
            cursor: pointer;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            flex: 1;
        }

        .control-btn i {
            font-size: 20px;
            margin-bottom: 4px;
        }

        /* 字体大小调整弹窗 */
        .font-modal {
            position: fixed;
            bottom: 70px;
            left: 50%;
            transform: translateX(-50%);
            background-color: var(--control-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 16px;
            width: 240px;
            display: none;
            flex-direction: column;
            gap: 12px;
            z-index: 102;
        }

        .font-modal.show {
            display: flex;
        }

        .font-size-btn {
            padding: 8px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            background-color: transparent;
            color: var(--text-color);
            cursor: pointer;
        }

        .font-size-btn.active {
            border-color: #2196f3;
            color: #2196f3;
        }

        /* 皮肤选择弹窗 */
        .skin-modal {
            position: fixed;
            bottom: 70px;
            left: 50%;
            transform: translateX(-50%);
            background-color: var(--control-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 16px;
            width: 240px;
            display: none;
            flex-direction: column;
            gap: 12px;
            z-index: 102;
        }

        .skin-modal.show {
            display: flex;
        }

        .skin-btn {
            padding: 8px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            background-color: transparent;
            color: var(--text-color);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .skin-btn.active {
            border-color: #2196f3;
            color: #2196f3;
        }

        .skin-indicator {
            width: 16px;
            height: 16px;
            border-radius: 4px;
        }

        /* 进度条 */
        .progress-container {
            position: fixed;
            top: 50px;
            left: 0;
            right: 0;
            height: 3px;
            background-color: transparent;
            z-index: 100;
            display: none; /* 初始隐藏 */
        }

        .progress-bar {
            height: 100%;
            background-color: #2196f3;
            width: 0%;
            transition: width 0.1s;
        }

        /* 新增：加载指示器样式 */
        .loading-indicator {
            position: fixed;
            bottom: 80px; /* 调整位置，避免被底部控制栏遮挡 */
            left: 50%;
            transform: translateX(-50%);
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            display: none;
            align-items: center;
            gap: 8px;
            z-index: 99;
        }

        .loading-indicator.show {
            display: flex;
        }

        .spinner {
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
    <!-- 引入图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <!-- 文件选择区域 -->
    <div class="file-selector" id="fileSelector">
        <h2>请选择书籍JSON文件</h2>
        <p>支持符合格式的书籍JSON文件</p>
        <button class="file-btn" id="fileBtn">选择文件</button>
        <input type="file" class="file-input" id="fileInput" accept=".json">
    </div>

    <!-- 进度条 -->
    <div class="progress-container" id="progressContainer">
        <div class="progress-bar" id="progressBar"></div>
    </div>

    <!-- 顶部导航 -->
    <header class="header" id="header">
        <button class="menu-btn" id="menuBtn">
            <i class="fas fa-bars"></i>
        </button>
        <div class="book-title" id="bookTitle">小王子</div>
    </header>

    <!-- 侧边章节栏 -->
    <aside class="sidebar" id="sidebar">
        <ul class="chapter-list" id="chapterList">
            <!-- 章节列表由JS动态生成 -->
        </ul>
    </aside>

    <!-- 遮罩层 -->
    <div class="overlay" id="overlay"></div>

    <!-- 图片查看器 -->
    <div class="image-viewer" id="imageViewer">
        <button class="close-btn" id="closeImageViewer">
            <i class="fas fa-times"></i>
        </button>
        <img src="" alt="大图预览" id="viewerImage">
    </div>

    <!-- 加载指示器 -->
    <div class="loading-indicator" id="loadingIndicator">
        <div class="spinner"></div>
        <span>加载中...</span>
    </div>

    <!-- 主阅读区域 -->
    <main class="reader-container" id="readerContainer">
        <div class="content" id="content">
            <!-- 阅读内容由JS动态加载 -->
        </div>
    </main>

    <!-- 底部控制栏 -->
    <footer class="control-bar" id="controlBar">
        <button class="control-btn" id="fontBtn">
            <i class="fas fa-text-height"></i>
            <span>字体</span>
        </button>
        <button class="control-btn" id="skinBtn">
            <i class="fas fa-palette"></i>
            <span>皮肤</span>
        </button>
        <button class="control-btn" id="prevBtn">
            <i class="fas fa-chevron-left"></i>
            <span>上章</span>
        </button>
        <button class="control-btn" id="nextBtn">
            <i class="fas fa-chevron-right"></i>
            <span>下章</span>
        </button>
    </footer>

    <!-- 字体大小调整弹窗 -->
    <div class="font-modal" id="fontModal">
        <button class="font-size-btn" data-size="14">小</button>
        <button class="font-size-btn active" data-size="16">中</button>
        <button class="font-size-btn" data-size="18">大</button>
        <button class="font-size-btn" data-size="20">特大</button>
    </div>

    <!-- 皮肤选择弹窗 -->
    <div class="skin-modal" id="skinModal">
        <button class="skin-btn active" data-skin="default">
            <span>白天模式</span>
            <span class="skin-indicator" style="background-color: #f7f7f7;"></span>
        </button>
        <button class="skin-btn" data-skin="night">
            <span>夜间模式</span>
            <span class="skin-indicator" style="background-color: #1a1a1a;"></span>
        </button>
        <button class="skin-btn" data-skin="eye-green">
            <span>护眼绿</span>
            <span class="skin-indicator" style="background-color: #e6f4ea;"></span>
        </button>
        <button class="skin-btn" data-skin="eye-yellow">
            <span>护眼黄</span>
            <span class="skin-indicator" style="background-color: #FFFDE7;"></span>
        </button>
        <button class="skin-btn" data-skin="eye-brown">
            <span>护眼褐</span>
            <span class="skin-indicator" style="background-color: #f5f0e8;"></span>
        </button>
    </div>

    <script>
        // 1. 书籍数据初始化为空
        let bookData = {};

        // 2. 全局状态管理
        const state = {
            currentChapter: 0, // 当前章节索引
            fontSize: 16, // 默认字体大小
            skin: 'default', // 默认皮肤
            scrollTop: 0, // 上次阅读滚动位置
            isLoading: false, // 是否正在加载章节
            lastScrollY: 0, // 上一次滚动位置，用于判断滚动方向
            hasMoreChapters: true // 是否还有更多章节
        };

        // 3. DOM元素获取
        const elements = {
            // 文件选择相关元素
            fileSelector: document.getElementById('fileSelector'),
            fileBtn: document.getElementById('fileBtn'),
            fileInput: document.getElementById('fileInput'),
            
            // 加载指示器
            loadingIndicator: document.getElementById('loadingIndicator'),
            
            // 原有元素
            menuBtn: document.getElementById('menuBtn'),
            sidebar: document.getElementById('sidebar'),
            overlay: document.getElementById('overlay'),
            chapterList: document.getElementById('chapterList'),
            content: document.getElementById('content'),
            bookTitle: document.getElementById('bookTitle'),
            fontBtn: document.getElementById('fontBtn'),
            fontModal: document.getElementById('fontModal'),
            fontSizeBtns: document.querySelectorAll('.font-size-btn'),
            skinBtn: document.getElementById('skinBtn'),
            skinModal: document.getElementById('skinModal'),
            skinBtns: document.querySelectorAll('.skin-btn'),
            prevBtn: document.getElementById('prevBtn'),
            nextBtn: document.getElementById('nextBtn'),
            progressBar: document.getElementById('progressBar'),
            progressContainer: document.getElementById('progressContainer'),
            imageViewer: document.getElementById('imageViewer'),
            viewerImage: document.getElementById('viewerImage'),
            closeImageViewer: document.getElementById('closeImageViewer'),
            readerContainer: document.getElementById('readerContainer'),
            header: document.getElementById('header'),
            controlBar: document.getElementById('controlBar')
        };

        // 4. 初始化函数
        function init() {
            // 绑定文件选择事件
            bindFileEvents();
        }

        // 5. 绑定文件选择相关事件
        function bindFileEvents() {
            // 点击选择文件按钮触发文件输入框
            elements.fileBtn.addEventListener('click', () => {
                elements.fileInput.click();
            });

            // 监听文件选择
            elements.fileInput.addEventListener('change', handleFileSelect);
        }

        // 6. 处理文件选择
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (!file) return;

            // 验证文件类型
            if (!file.name.endsWith('.json')) {
                alert('请选择JSON格式的文件');
                return;
            }

            const reader = new FileReader();
            
            reader.onload = function(e) {
                try {
                    // 解析JSON文件
                    const jsonData = JSON.parse(e.target.result);
                    
                    // 验证JSON结构
                    if (!jsonData.title || !jsonData.chapters || !Array.isArray(jsonData.chapters)) {
                        throw new Error('JSON格式不正确，缺少必要字段');
                    }
                    
                    // 保存书籍数据
                    bookData = jsonData;
                    
                    // 更新是否有更多章节的状态
                    state.hasMoreChapters = bookData.chapters.length > 1;
                    
                    // 移除文件选择区域，显示阅读器
                    elements.fileSelector.style.display = 'none';
                    showReader();
                    
                    // 初始化阅读器
                    initReader();
                    
                } catch (error) {
                    alert('文件解析错误: ' + error.message);
                    console.error('文件解析错误:', error);
                }
            };
            
            reader.onerror = function() {
                alert('文件读取失败，请重试');
            };
            
            // 读取文件内容
            reader.readAsText(file);
        }

        // 7. 显示阅读器界面
        function showReader() {
            elements.header.style.display = 'flex';
            elements.sidebar.style.display = 'block';
            elements.overlay.style.display = 'block';
            elements.readerContainer.style.display = 'block';
            elements.controlBar.style.display = 'flex';
            elements.progressContainer.style.display = 'block';
        }

        // 8. 初始化阅读器
        function initReader() {
            // 加载书籍标题
            elements.bookTitle.textContent = bookData.title;
            
            // 生成章节列表
            renderChapterList();
            
            // 从localStorage恢复阅读进度
            loadReadingProgress();
            
            // 应用保存的皮肤设置
            applySkin(state.skin);
            
            // 加载当前章节内容
            loadCurrentChapter();
            
            // 绑定事件监听
            bindEvents();
        }

        // 9. 生成章节列表
        function renderChapterList() {
            elements.chapterList.innerHTML = '';
            bookData.chapters.forEach((chapter, index) => {
                const li = document.createElement('li');
                li.className = `chapter-item ${index === state.currentChapter ? 'active' : ''}`;
                li.textContent = chapter.title;
                li.dataset.index = index; // 存储章节索引
                elements.chapterList.appendChild(li);
            });
        }

        // 10. 加载当前章节内容（支持文本和图片）
        function loadCurrentChapter() {
            // 显示加载指示器
            showLoading();
            
            // 使用setTimeout模拟加载延迟
            setTimeout(() => {
                const chapter = bookData.chapters[state.currentChapter];
                if (!chapter) {
                    hideLoading();
                    return;
                }
                
                // 清空内容区
                elements.content.innerHTML = '';
                
                // 遍历内容，根据类型生成对应的元素
                chapter.content.forEach(item => {
                    if (item.type === 'text') {
                        // 文本段落
                        const p = document.createElement('p');
                        p.textContent = item.content;
                        elements.content.appendChild(p);
                    } else if (item.type === 'image') {
                        // 图片
                        const imageContainer = document.createElement('div');
                        imageContainer.className = 'image-container';
                        
                        const img = document.createElement('img');
                        img.src = item.src;
                        img.alt = item.alt || '插图';
                        img.dataset.src = item.src; // 存储原始图片地址用于放大查看
                        
                        // 如果有图片说明，添加说明文字
                        if (item.caption) {
                            const caption = document.createElement('div');
                            caption.className = 'image-caption';
                            caption.textContent = item.caption;
                            imageContainer.appendChild(caption);
                        }
                        
                        imageContainer.insertBefore(img, imageContainer.firstChild);
                        elements.content.appendChild(imageContainer);
                    }
                });
                
                // 设置字体大小
                elements.content.style.fontSize = `${state.fontSize}px`;
                
                // 确保页面滚动到顶部
                setTimeout(() => {
                    window.scrollTo({
                        top: 0,
                        behavior: 'auto' // 直接跳转，无动画
                    });
                    state.scrollTop = 0; // 重置滚动位置记录
                }, 100);
                
                // 更新章节列表高亮
                updateChapterActive();
                
                // 更新是否有更多章节的状态
                state.hasMoreChapters = state.currentChapter < bookData.chapters.length - 1;
                
                // 隐藏加载指示器
                hideLoading();
            }, 500);
        }

        // 11. 更新章节列表高亮
        function updateChapterActive() {
            document.querySelectorAll('.chapter-item').forEach((item, index) => {
                item.classList.toggle('active', index === state.currentChapter);
            });
        }

        // 12. 保存阅读进度到localStorage
        function saveReadingProgress() {
            const progress = {
                currentChapter: state.currentChapter,
                scrollTop: window.scrollY,
                fontSize: state.fontSize,
                skin: state.skin
            };
            localStorage.setItem('readerProgress', JSON.stringify(progress));
        }

        // 13. 从localStorage加载阅读进度
        function loadReadingProgress() {
            const progress = localStorage.getItem('readerProgress');
            if (progress) {
                const parsed = JSON.parse(progress);
                state.currentChapter = parsed.currentChapter || 0;
                state.scrollTop = parsed.scrollTop || 0;
                state.fontSize = parsed.fontSize || 16;
                state.skin = parsed.skin || 'default';
                
                // 更新字体大小按钮状态
                elements.fontSizeBtns.forEach(btn => {
                    if (parseInt(btn.dataset.size) === state.fontSize) {
                        btn.classList.add('active');
                    } else {
                        btn.classList.remove('active');
                    }
                });
            }
        }

        // 14. 更新阅读进度条
        function updateProgressBar() {
            const totalHeight = document.body.scrollHeight - window.innerHeight;
            const progress = (window.scrollY / totalHeight) * 100;
            elements.progressBar.style.width = `${progress}%`;
        }

        // 15. 打开图片查看器
        function openImageViewer(src) {
            elements.viewerImage.src = src;
            elements.imageViewer.classList.add('show');
            // 阻止页面滚动
            document.body.style.overflow = 'hidden';
        }

        // 16. 关闭图片查看器
        function closeImageViewer() {
            elements.imageViewer.classList.remove('show');
            elements.viewerImage.src = '';
            // 恢复页面滚动
            document.body.style.overflow = '';
        }

        // 17. 显示加载指示器
        function showLoading() {
            state.isLoading = true;
            elements.loadingIndicator.classList.add('show');
        }

        // 18. 隐藏加载指示器
        function hideLoading() {
            state.isLoading = false;
            elements.loadingIndicator.classList.remove('show');
        }

        // 19. 检测是否滚动到页面底部
        function isNearBottom() {
            // 增加敏感度，当距离底部100px时就认为接近底部
            return window.innerHeight + window.scrollY >= document.body.scrollHeight - 100;
        }

        // 20. 自动加载下一章
        function autoLoadNextChapter() {
            if (state.isLoading || !state.hasMoreChapters) return;
            
            // 检查是否还有下一章
            if (state.currentChapter < bookData.chapters.length - 1) {
                state.currentChapter++;
                loadCurrentChapter(); // 加载下一章，会自动滚动到顶部
                saveReadingProgress();
            } else {
                state.hasMoreChapters = false;
            }
        }

        // 21. 应用皮肤设置
        function applySkin(skin) {
            // 移除所有皮肤类
            document.body.classList.remove('night', 'eye-green', 'eye-yellow', 'eye-brown');
            
            // 应用选中的皮肤
            if (skin !== 'default') {
                document.body.classList.add(skin);
            }
            
            // 更新按钮状态
            elements.skinBtns.forEach(btn => {
                if (btn.dataset.skin === skin) {
                    btn.classList.add('active');
                } else {
                    btn.classList.remove('active');
                }
            });
            
            // 保存皮肤设置
            state.skin = skin;
            saveReadingProgress();
        }

        // 22. 绑定所有事件
        function bindEvents() {
            // 侧边栏展开/收起
            elements.menuBtn.addEventListener('click', () => {
                elements.sidebar.classList.add('show');
                elements.overlay.classList.add('show');
            });
            
            elements.overlay.addEventListener('click', () => {
                elements.sidebar.classList.remove('show');
                elements.overlay.classList.remove('show');
                elements.fontModal.classList.remove('show');
                elements.skinModal.classList.remove('show');
            });
            
            // 章节切换（点击章节列表）
            elements.chapterList.addEventListener('click', (e) => {
                const chapterItem = e.target.closest('.chapter-item');
                if (chapterItem) {
                    const index = parseInt(chapterItem.dataset.index);
                    state.currentChapter = index;
                    loadCurrentChapter(); // 加载章节，会自动滚动到顶部
                    elements.sidebar.classList.remove('show');
                    elements.overlay.classList.remove('show');
                    saveReadingProgress();
                }
            });
            
            // 字体大小调整弹窗
            elements.fontBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                elements.fontModal.classList.toggle('show');
                elements.skinModal.classList.remove('show');
            });
            
            // 选择字体大小
            elements.fontSizeBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    const size = parseInt(btn.dataset.size);
                    state.fontSize = size;
                    elements.content.style.fontSize = `${size}px`;
                    
                    // 更新按钮高亮
                    elements.fontSizeBtns.forEach(b => b.classList.remove('active'));
                    btn.classList.add('active');
                    
                    // 关闭弹窗并保存进度
                    elements.fontModal.classList.remove('show');
                    saveReadingProgress();
                });
            });
            
            // 皮肤选择弹窗
            elements.skinBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                elements.skinModal.classList.toggle('show');
                elements.fontModal.classList.remove('show');
            });
            
            // 选择皮肤
            elements.skinBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    const skin = btn.dataset.skin;
                    applySkin(skin);
                    elements.skinModal.classList.remove('show');
                });
            });
            
            // 上一章/下一章切换
            elements.prevBtn.addEventListener('click', () => {
                if (state.currentChapter > 0) {
                    state.currentChapter--;
                    loadCurrentChapter(); // 加载章节，会自动滚动到顶部
                    saveReadingProgress();
                }
            });
            
            elements.nextBtn.addEventListener('click', () => {
                if (state.currentChapter < bookData.chapters.length - 1) {
                    state.currentChapter++;
                    loadCurrentChapter(); // 加载章节，会自动滚动到顶部
                    saveReadingProgress();
                }
            });
            
            // 滚动事件：更新进度条 + 保存滚动位置 + 检测底部自动加载
            window.addEventListener('scroll', () => {
                // 更新进度条
                updateProgressBar();
                
                // 记录滚动方向和位置
                const isScrollingDown = window.scrollY > state.lastScrollY;
                state.lastScrollY = window.scrollY;
                
                // 检测是否到达底部且正在向下滚动，自动加载下一章
                if (false) {
                    if (isScrollingDown && isNearBottom() && !state.isLoading && state.hasMoreChapters) {
                        const lastEle = document.getElementById("last-space");
                        if (!lastEle) {
                            const div = document.createElement('div');
                            div.id = "last-space";
                            div.time = "" + Date.now();
                            div.style.height = "30px";
                            elements.content.appendChild(div);
                        } else {
                            let timestamp = Date.now();
                            let time = lastEle.time;
                            if (timestamp - time > 800) {
                                autoLoadNextChapter();
                            }
                        }
                    }
                }
                
                // 防抖处理：避免频繁保存（每300ms保存一次）
                clearTimeout(window.scrollTimer);
                window.scrollTimer = setTimeout(() => {
                    state.scrollTop = window.scrollY;
                    saveReadingProgress();
                }, 300);
            });
            
            // 点击图片放大查看
            elements.content.addEventListener('click', (e) => {
                const img = e.target.closest('img');
                if (img && img.dataset.src) {
                    openImageViewer(img.dataset.src);
                }
            });
            
            // 关闭图片查看器
            elements.closeImageViewer.addEventListener('click', closeImageViewer);
            
            // 点击图片查看器背景关闭
            elements.imageViewer.addEventListener('click', (e) => {
                if (e.target === elements.imageViewer) {
                    closeImageViewer();
                }
            });
            
            // 按ESC键关闭图片查看器
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && elements.imageViewer.classList.contains('show')) {
                    closeImageViewer();
                }
            });
            
            // 点击其他区域关闭弹窗
            document.addEventListener('click', (e) => {
                if (!elements.fontBtn.contains(e.target) && !elements.fontModal.contains(e.target) &&
                    !elements.skinBtn.contains(e.target) && !elements.skinModal.contains(e.target)) {
                    elements.fontModal.classList.remove('show');
                    elements.skinModal.classList.remove('show');
                }
            });
        }

        // 启动应用
        window.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>
